package com.sunchangpeng.wechat.mp;

import com.sunchangpeng.wechat.core.exception.WechatClientException;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class EndpointProvider {
    private static Properties endpoints;

    private static synchronized void loadProperties() {
        if (endpoints == null) {
            try {
                Properties properties = new Properties();
                InputStream inputStream = EndpointProvider.class.getClassLoader().getResourceAsStream("wechat-mp-endpoint.properties");
                properties.load(inputStream);
                endpoints = properties;
            } catch (IOException e) {
                throw new WechatClientException("cannot find resource wechat-mp-endpoint.properties from classpath.", e);
            }
        }
    }

    public static String get(String key) {
        if (endpoints == null) {
            loadProperties();
        }

        String endpoint = endpoints.getProperty(key);
        if (StringUtils.isBlank(endpoint)) {
            throw new WechatClientException("cannot find endpoint from wechat-mp-endpoint.properties");
        }
        return endpoint;
    }
}
